package com.happyfamily.springboot.crowdsourcingplatform.service.guo.impl;

import com.happyfamily.springboot.crowdsourcingplatform.dao.guo.FrontNeedDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.guo.ServiceDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.sun.NewDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.sun.SysUserDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.weng.NeedDao;
import com.happyfamily.springboot.crowdsourcingplatform.model.*;
import com.happyfamily.springboot.crowdsourcingplatform.service.guo.FrontNeedService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Transactional

public class FrontNeedServiceImpl implements FrontNeedService
{

	@Autowired(required = false)
	FrontNeedDao frontNeedDao;

	@Autowired(required = false)
	private ServiceDao serviceDao;

	@Autowired(required = false)
	private NewDao newDao;

	@Autowired(required = false)
	private SysUserDao sysUserDao;


	@Override
	public int total(String name, String ntitle, String startDate, String endDate)
	{
		int n=frontNeedDao.getNeedListCount(name,ntitle,startDate,endDate);
		return n;
	}

	@Override
	public List<Need> search(RowBounds rowBounds, String name, String ntitle, String startDate, String endDate)
	{
		List<Need> list=frontNeedDao.getNeedList(rowBounds,name,ntitle,startDate,endDate);
		return list;
	}

	@Override
	public int totalWork(String consumeraccount, String wtitle, String startDate, String endDate)
	{
		int n=frontNeedDao.getWorkListCount(consumeraccount,wtitle,startDate,endDate);
		return n;
	}

	@Override
	public List<Work> searchWork(RowBounds rowBounds, String consumeraccount, String wtitle, String startDate, String endDate)
	{
		List<Work> list=frontNeedDao.getWorkList(rowBounds,consumeraccount,wtitle,startDate,endDate);
		return list;
	}

	@Override
	public Work getWork(String wid)
	{
		return frontNeedDao.getWork(wid);
	}

	@Override
	public List<Tender> getTenderList(Long needid)
	{
		return frontNeedDao.getTenderList(needid);
	}

	@Override
	public SysUser getUserList(Long uid)
	{

		return frontNeedDao.getUserList(uid);
	}

	@Override
	public List<StationFlow> getMoney(RowBounds rowBounds,String account,String startDate)
	{
		return  frontNeedDao.getMoneyList(rowBounds,account,startDate);

	}

	@Override
	public int totalMoney(String account, String startDate)
	{

		return frontNeedDao.moneyCount(account,startDate);
	}

	@Override
	public SysUser getUser(String account)
	{
		return frontNeedDao.getUser(account);
	}

	@Override
	public String charge(String account, String msg)
	{
		String str="";
		Date t = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		df.format(t);

		int n =frontNeedDao.addMoney("用户充值",msg,df.format(t),account,account,msg);
		if (n>0){
			Double m=Double.valueOf(frontNeedDao.getUser(account).getUmoney())+Double.valueOf(msg);
			int j=frontNeedDao.changeMoney(String.valueOf(m),account);
			if (j>0){
				str="yes";
			}

		}else{
			str="no";
		}
		return str;
	}

	@Override
	public List<ServerType> getServerType(Long sparentid)
	{
		return frontNeedDao.getServerType(sparentid);
	}

	@Override
	public String confirmServiceProvider(Long nid, Long tid,String account)
	{
		String str="";
		Need need=frontNeedDao.getNeed(nid);


		Date d = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String currdate = format.format(d);
		Calendar ca = Calendar.getInstance();
		ca.add(Calendar.DATE, Integer.valueOf(need.getNrealtime()));// num为增加的天数，可以改变的
		d = ca.getTime();
		String enddate = format.format(d);

		String f="";
		if (Integer.valueOf(need.getNmoney())<=1000){
			   f="5";
		}else if (Integer.valueOf(need.getNmoney())<=5000){
               f="4";
		}else if (Integer.valueOf(need.getNmoney())<=10000){
			   f="3";
		}else if (Integer.valueOf(need.getNmoney())<=15000){
			   f="2";
		}else if (Integer.valueOf(need.getNmoney())>15000){
			   f="1";
		}
		int m=frontNeedDao.addOrder(nid,8,currdate,need.getNrealtime(),Long.valueOf(f),account);

		int j=frontNeedDao.updateTender(currdate,tid);


		Tender tender=frontNeedDao.getTender(nid);
		SysUser user=null;
		if (tender.getTtype().equals("个人投标")){
			user=frontNeedDao.getUserList(tender.getUserid());

		}else{
			Alliance alliance=frontNeedDao.getAlliance(tender.getUserid());
			user=frontNeedDao.getUserList(Long.valueOf(alliance.getAmasterid()));
		}
		News news=new News();
		news.setNtime(currdate);
		news.setUaccount(user.getUaccount());
		news.setNtext("您投标的"+need.getNtitle()+"的需求已中标");
		newDao.addNews(news);
		sysUserDao.updateCount(user.getUaccount(),user.getNewcount()+1);

		List<Tender> tenders=frontNeedDao.getTenderListByNeedid(nid);
		for (int i = 0; i <tenders.size() ; i++)
		{
			SysUser userGuo=null;
			if (tenders.get(i).getTtype().equals("个人投标")){
				userGuo=frontNeedDao.getUserList(tenders.get(i).getUserid());
			}else{
				Alliance allianceGuo=frontNeedDao.getAlliance(tenders.get(i).getUserid());
				userGuo=frontNeedDao.getUserList(Long.valueOf(allianceGuo.getAmasterid()));
			}
			News newsGuo=new News();
			newsGuo.setNtime(currdate);
			newsGuo.setUaccount(userGuo.getUaccount());
			newsGuo.setNtext("您投标的"+need.getNtitle()+"的需求未中标");
			newDao.addNews(newsGuo);
			sysUserDao.updateCount(userGuo.getUaccount(),userGuo.getNewcount()+1);

		}



		int k=frontNeedDao.updateNeed("已中标",nid);

		if (m>0&&j>0&&k>0){

			Orders orders=serviceDao.getOrder(nid);
			int fuck=frontNeedDao.addOrderFrom(orders.getOid(),currdate,"订单生成,订单状态为待付款");

			str="yes";
		}else{
			str="no";
		}
		return str;
	}

	@Override
	public Alliance getAlliance(Long uid)
	{
		return frontNeedDao.getAlliance(uid);
	}

	@Override
	public ServerType getType(Long sid)
	{
		return frontNeedDao.getType(sid);
	}

	@Override
	public List<Orders> searchOrders(RowBounds rowBounds, String account, String startDate, String endDate)
	{
		return frontNeedDao.getOrderList(rowBounds,account,startDate,endDate);
	}

	@Override
	public int totalOrders(String account, String startDate, String endDate)
	{
		return frontNeedDao.getOrderListCount(account,startDate,endDate);
	}

	@Override
	public Need getNeed(Long nid)
	{
		return frontNeedDao.getNeed(nid);
	}

	@Override
	public Parameter getParameterTypeOne(Long pid)
	{
		return frontNeedDao.getParameterTypeOne(pid);
	}

	@Override
	public String payMoneyWork(String account,String wid)
	{
		String str="no";
		Work work=frontNeedDao.getWork(wid);
        Parameter parameter=frontNeedDao.getParameter(Long.valueOf(wid),account);
        Orders orders=frontNeedDao.getOrdder(Long.valueOf(wid),account);
        SysUser user=frontNeedDao.getUser(account);

        String p=parameter.getPname();
        String wMoney=work.getWmoney();
        String wAccount=work.getWuseraccount();



		Double k=Double.valueOf(wMoney);
		Double n=Double.valueOf(p)/100;
		Double j=k*n;
		Double m=k-j;


        if (Double.valueOf(user.getUmoney())>Double.valueOf(work.getWmoney()))
        {
	        Date d = new Date();
	        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	        String currdate = format.format(d);
	        //服务商的一系列操作
	        //获取服务商信息
	        SysUser user1 = frontNeedDao.getUser(work.getWuseraccount());
	        //根据原来的金钱加上收入的得到总金额
	        Double mm = Double.valueOf(user1.getUmoney()) + m;
	        //根据账号更改金额
	        int mm1 = frontNeedDao.changeMoney(String.valueOf(mm), work.getWuseraccount());
	        //添加交易数据
	        int mm2 = frontNeedDao.addMoney("服务商作品收入", String.valueOf(k), currdate, work.getWuseraccount(), account, String.valueOf(m));

	        //用户的一系列操作
	        //用户原来的金钱减去支出的得到总金额
	        Double kk = Double.valueOf(user.getUmoney()) - k;
	        //根据账号更改金额
	        int kk1 = frontNeedDao.changeMoney(String.valueOf(kk), account);
	        //添加交易数据
	        int kk2 = frontNeedDao.addMoney("用户购买作品", String.valueOf(k), currdate, "55555555", account, String.valueOf(j));

	        //土豪家族操作
	        BankAccount bankAccount = frontNeedDao.getBankAccount("55555555");
	        //土豪家族盈利以及本金
	        Double jj = Double.valueOf(bankAccount.getBmoney()) + j;
	        //根据账号更改金额
	        int jj1 = frontNeedDao.updateBankAccount(String.valueOf(jj), "55555555");
	        //添加交易数据
	        int jj2 = frontNeedDao.addMoney("作品交易完成，平台抽成", String.valueOf(j), currdate, "55555555", account, String.valueOf(j));

	        int nmjk = frontNeedDao.changeOrderType(Long.valueOf(4), Long.valueOf(wid), account);

	        if (Integer.valueOf(user1.getUscore()) < 100)
	        {

		        frontNeedDao.changeUserScore(Integer.valueOf(user1.getUscore()) + 1 + "", user1.getUaccount());
	        }

	        int nmjk1 = frontNeedDao.changeOrderEndTime(currdate, Long.valueOf(wid), account);

	        frontNeedDao.addOrderFrom(orders.getOid(),currdate,"雇主对作品付款，作品交易完成");

	        if (mm1 > 0 && mm2 > 0 && kk1 > 0 && kk2 > 0 && jj1 > 0 && jj2 > 0 && nmjk > 0 && nmjk1 > 0)
	        {
		        str = "yes";
	        } else
	        {
		        str = "no";
	        }
        }else {
	        str = "no";
        }

		return str;
	}

	@Override
	public String payMoneyNeed(Long nid,String account,Long oid)
	{
		String str="";
		Tender tender=frontNeedDao.getTender(nid);
		SysUser sysUser=frontNeedDao.getUser(account);
		Need need=frontNeedDao.getNeed(nid);
		if (Double.valueOf(sysUser.getUmoney())>Double.valueOf(need.getNmoney())){
			Double money=Double.valueOf(sysUser.getUmoney());
			Double money2=Double.valueOf(need.getNmoney());
			Double money3=money-money2;
			Date d = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String currdate = format.format(d);
			int n=frontNeedDao.changeMoney(String.valueOf(money3),account);
			int n1=frontNeedDao.addMoney("用户需求订单付款",String.valueOf(-money2),currdate,"44444444",account,String.valueOf(money2));

			BankAccount bankAccount=frontNeedDao.getBankAccount("44444444");
			Double money1=Double.valueOf(bankAccount.getBmoney());
			Double money4=money1+money2;
			int m=frontNeedDao.updateBankAccount(String.valueOf(money4),"44444444");
			int m1=frontNeedDao.addMoney("需求账号收款",String.valueOf(money2),currdate,"44444444",account,String.valueOf(money2));

			int j=frontNeedDao.changeOrderTypeByOid(Long.valueOf(10),oid);
			Orders orders=frontNeedDao.getOrdersByOid(oid);
			Calendar ca = Calendar.getInstance();
			ca.add(Calendar.DATE, Integer.valueOf(orders.getOrealtime()));// num为增加的天数，可以改变的
			d = ca.getTime();
			String enddate = format.format(d);
			int j1=frontNeedDao.changeOrderEndTimeByOid(enddate,oid);


			if (n>0&&n1>0&&m>0&&m1>0&&j>0&&j1>0){
				frontNeedDao.addOrderFrom(oid,currdate,"雇主对订单进行付款,订单开始进行");

				str="yes";
			}else{
				str="no";
			}
		}else{
			str="no";
		}
		return str;
	}


	@Override
	public String delivery(String nid,String oid,String account)
	{
		String str="";
		Date d = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String currdate = format.format(d);
		Tender tender=frontNeedDao.getTender(Long.valueOf(nid));
		//先拿到需求暂存的账户
		BankAccount bankAccount=frontNeedDao.getBankAccount("44444444");
		//拿到服务商账号
		SysUser user=frontNeedDao.getUser(account);
		//拿到需求对象
		Need need=frontNeedDao.getNeed(Long.valueOf(nid));
		//拿到需求账户的钱
		BankAccount bankAccount1=frontNeedDao.getBankAccount("66666666");
		//拿到参数对象
		Parameter parameter=frontNeedDao.getParameterByOid(Long.valueOf(oid));
		//拿到项目所需要的钱
		Double money=Double.valueOf(need.getNmoney());
		Double k=Double.valueOf(money);
		//获取暂存账户的金额
		Double money1=Double.valueOf(bankAccount.getBmoney());
		Double j=Double.valueOf(money1);
		//获取服务商的资金
		Double money2=Double.valueOf(user.getUmoney());
		Double z=Double.valueOf(money2);
		//获取需求账户的钱
		Double money3=Double.valueOf(bankAccount1.getBmoney());
		Double m=Double.valueOf(money3);
		//获取抽成点数
		String p=parameter.getPname();
		Double n=Double.valueOf(p)/100;
		//操作平台金额
		//平台赚取的金额
		Double m1=k*n;
		//需求账户上更改的金额
		Double m2=m1+m;
		//暂存账户金额更改
		Double j1=j-k;

		if (tender.getTtype().equals("个人投标")){


			int mm=frontNeedDao.updateBankAccount(String.valueOf(m2),"66666666");
			int mmm=frontNeedDao.addMoney("需求完成,平台提成",String.valueOf(m1),currdate,"66666666","44444444",String.valueOf(m1));

			int jj=frontNeedDao.updateBankAccount(String.valueOf(j1),"44444444");
			//服务商获取的金额
			Double zz=k-m1;
			Double zzz=zz+z;
			int jjj=frontNeedDao.addMoney("订单交易完成,对服务商进行打款",String.valueOf(-zz),currdate,account,"44444444",String.valueOf(-zz));
			int zzzz=frontNeedDao.changeMoney(String.valueOf(zzz),account);

			//更改订单状态
			int mjz=frontNeedDao.changeOrderTypeByOid(Long.valueOf(4),Long.valueOf(oid));
			if (Integer.valueOf(user.getUscore())<100){
				frontNeedDao.changeUserScore(Integer.valueOf(user.getUscore())+1+"",user.getUaccount());

			}
			if (mm>0&&mmm>0&&jj>0&&jjj>0&&zzzz>0&&mjz>0){
				frontNeedDao.addOrderFrom(Long.valueOf(oid),currdate,"服务商完成订单发货,订单完成");
				str="yes";
			}else{
				str="no";
			}

		}else{


			//获取联盟id
			Long useraid=tender.getUserid();
			Alliance alliance=frontNeedDao.getAlliance(useraid);
			//获取改联盟的所有对象
			List<User_alliance> user_alliances=frontNeedDao.getUsers(useraid);
			ArrayList<SysUser> sysUsers=new ArrayList<>();
			for (User_alliance ua : user_alliances)
			{
				if(ua.getUastate().equals("运行中"))
				{
					//根据uid获取用户对象
					SysUser user1=frontNeedDao.getUserList(ua.getUid());
					sysUsers.add(user1);
				}
			}
			String moneyAverage=new DecimalFormat("#.00").format(((1.00*(k-m1))/sysUsers.size()));
			for (int i = 0; i <sysUsers.size(); i++)
			{
				//获取该对象的金钱
				Double dx=Double.valueOf(sysUsers.get(i).getUmoney());
				Double dx1=Double.valueOf(moneyAverage)+dx;
				frontNeedDao.changeMoney(String.valueOf(dx1),sysUsers.get(i).getUaccount());
				frontNeedDao.addMoney("需求获利",+Double.valueOf(moneyAverage)+"",currdate,sysUsers.get(i).getUaccount(),"44444444",+Double.valueOf(moneyAverage)+"");

			}
			//更改订单状态
			int mjz=frontNeedDao.changeOrderTypeByOid(Long.valueOf(4),Long.valueOf(oid));
			if (Integer.valueOf(user.getUscore())<100){
				frontNeedDao.changeUserScore(Integer.valueOf(user.getUscore())+1+"",user.getUaccount());

			}
			int jjj=frontNeedDao.addMoney("订单交易完成,对联盟进行打款",String.valueOf(-(k-m1)),currdate,alliance.getAbank(),"44444444",String.valueOf(-(k-m1)));
			frontNeedDao.addOrderFrom(Long.valueOf(oid),currdate,"联盟完成订单发货,订单完成");

			  str="yes";

			}








		return str;
	}

	@Override
	public Orders getOrder(Long oid)
	{
		return frontNeedDao.getOrdersByOid(oid);
	}

	@Override
	public List<SysUser> getCounltantUsder(Long rid)
	{
		return frontNeedDao.getCounltantUsder(rid);
	}

	@Override
	public String determineMoney(String account, Long wid)
	{
		String str="no";
		Work work=frontNeedDao.getWork(String.valueOf(wid));
		SysUser user=frontNeedDao.getUser(account);
		if (Double.valueOf(user.getUmoney())>Double.valueOf(work.getWmoney())){
			str="yesdo";
		}else{
			str="nodo";
		}


		return str;
	}


}
